#include "RosterEntry.h"

#include "XMPPConnection.h"
#include "RosterGroup.h"
#include "Roster.h"


RosterPacket::Item * RosterEntry::toRosterItem( RosterEntry * entry) {
	RosterPacket::Item * item = new RosterPacket::Item(entry->getUser(), entry->getName());
	item->setItemType(entry->getType());
	item->setItemStatus(entry->getStatus());
	// Set the correct group names for the item.
	std::list<RosterGroup*> l = entry->getGroups();
	for (std::list<RosterGroup*>::iterator it = l.begin(); it != l.end(); it++) {
		item->addGroupName((*it)->getName());
	}
	return item;
}


RosterEntry::RosterEntry(std::string & user, std::string & name, RosterPacket::ITEM_TYPE type,
		RosterPacket::ItemStatus * status, XMPPConnection * connection) :
	user(user),
	name(name),
	type(type),
	status(status),
	connection(connection) {
}


void RosterEntry::setName(std::string & name) {
	// Do nothing if the name hasn't changed.
	if (!name.empty() && name == this->name) {
		return;
	}
	this->name = name;
	RosterPacket * packet = new RosterPacket();
	packet->setType(IQ::IQ_TYPE_SET);
	packet->addRosterItem(toRosterItem(this));
	connection->sendPacket(packet);
}


void RosterEntry::updateState(std::string & name, RosterPacket::ITEM_TYPE type, RosterPacket::ItemStatus * status) {
	this->name = name;
	this->type = type;
	this->status = status;
}


std::list<RosterGroup*> RosterEntry::getGroups() {
	std::list<RosterGroup*> results;
	// Loop through all roster groups and find the ones that contain this
	// entry. This algorithm should be fine
	std::list<RosterGroup*> groups = connection->getRoster()->getGroups();
	for ( std::list<RosterGroup*>::iterator it = groups.begin();
			it != groups.end(); it++) {
		if ((*it)->contains(this)) {
			results.push_back(*it);
		}
	}
	return results;
}



